package net.topicopedia.other;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class GetTopicsInCategoryServlet extends HttpServlet {
	@SuppressWarnings("null")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");
		
		String output = "[";
		
		String categoryString = (String) req.getParameter("category");
		
		if ( categoryString == "" || categoryString == null  )
		{
			output = "[]";
			resp.getWriter().println( output );
			return;
		}
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Key categoryKey = KeyFactory.createKey("Category", (Long) Long.parseLong(categoryString) );
		Entity category=null;
		try {
			category = datastore.get ( categoryKey );
		} catch (EntityNotFoundException e) {
			output = "[]";
			resp.getWriter().println( output );
			return;
		}
		
		JSONObject topicsObject=null;
		try {
			Text topicsText = (Text) category.getProperty("topics");
			String string = "";
			if ( topicsText != null )
			{
				string = "{'topics':";
				string += "[{\"uuid\": \"5277655813324800\", \"title\": \"Parthenon\", \"descriptor\": \"What is the Parthenon?\", \"category\": \"6210041673678848\", \"tags\": \"greece, parthenon, temple\"},";
				string += "{\"uuid\": \"6350779162034176\", \"title\": \"Zeus\", \"descriptor\": \"Who is Zeus?\", \"category\": \"4521191813414912\", \"tags\": \"greece, zeus,  god\"},";
				string += "{\"uuid\": \"4943404278480896\", \"title\": \"Hera\", \"descriptor\": \"Who is Hera?\", \"category\": \"5928566696968192\", \"tags\": \"greece, god\"}]";
				string += "}";		
			} else {
				string = topicsText.getValue();
			}
			topicsObject = new JSONObject( string );
		} catch (JSONException e) {
			output = "[]";
			resp.getWriter().println( output );
			return;
		}
		
		
		
		Query query = new Query("Category");
		PreparedQuery pq = datastore.prepare(query);
		
		if ( pq == null )
		{
			output = "[]";
			resp.getWriter().println( output );
			return;
		}
		
		for (Entity topic : pq.asIterable() ) {
			
			String topicCategory = topic.getProperty("category")+"";

			if ( topicCategory!= null && topicCategory.equals(category)){
				String storedUuid = topic.getKey().getId() + "";
				String storedTitle = (String) topic.getProperty("title");
				String storedDescriptor = (String) topic.getProperty("descriptor");
				String storedCategory = topic.getProperty("category")+"";
				@SuppressWarnings("unchecked")
				List<String> storedTagsList = (List<String>) topic.getProperty("tags");
				String storedTags="";
				for ( int t=0; t< storedTagsList.size(); t++)
				{
					String storedTag = storedTagsList.get(t);
					if ( storedTag != null )
					{
						if ( t > 0 )
						{
							storedTags += ", ";
						}
						storedTags += storedTag;
					}
				}
				String storedItems = (String)  topic.getProperty("items");
				String storedLinks = (String) topic.getProperty("links");
				
				if ( output.length() > 1 )
				{
					output += ", ";
				}
				
				output += "{\"uuid\": " + storedUuid;
				output += ", \"title\": " + "\"" + storedTitle + "\"";
				output += ", \"descriptor\": " + "\"" + storedDescriptor + "\"";
				output += ", \"category\": " + storedCategory;
				output += ", \"tags\": " + "\"" + storedTags + "\"";
				output += ", \"items\": " + storedItems;
				output += ", \"links\": " + storedLinks;
				output += "}";
			}
		}
		
		output += "]";
		
		resp.getWriter().println( output );
		
	}
}
 